/**********
    @name: thumb组件
    @describtion: 提供缩略图上传策略，可以接收一个图片数组其中选择，还可以在素材库中选择 并且进行裁剪
    @author:liubingye
    @date:2023-03-09 16:02:45
***********/
<template>
  <el-form-item :label="props.title" :rules="textRule" :prop="props.field">
    <div class="thumb-img-box" @click="handleShowThumbBox" :class="'thumb-img-box-'+props.imageScale">
      <div v-if="thumbImg" class="delete-thumb" @click.stop="deleteThumb">
        <el-icon><Delete /></el-icon>
      </div>
      <img v-if="thumbImg" :src="thumbImg" alt="">
      <el-icon v-else><Plus /></el-icon>
    </div>
    <el-dialog
        v-model="showThumbBox"
        title="缩略图处理"
        width="944px"
        class="thumb-tool-box"
        @close="handleCloseThumbBox"
    >
      <div class="image-choose-content">
        <div class="image-choose-step1" v-if="thumbStep === 1">
          <el-tabs v-model="thumbSelectMenu" class="thumb-tabs" @tab-change="handleTabChange">
            <el-tab-pane :label="grabField.name + '图片'" v-if="grabField" name="1">
              <div class="inner-image-choose">
                <h3>从{{grabField.name}}中选择图片：</h3>
                <el-scrollbar height="432px">
                  <div class="thumb-list-box" v-if="thumbList.length > 0">
                    <div class="thumb-item" v-for="item in thumbList" :key="item.id" @click="chooseThumb(item)">
                      <el-checkbox class="thumb-item-checkbox" :model-value="choseThumb[0].id === item.id"></el-checkbox>
                      <img :src="item.url" alt="">
                    </div>
                  </div>
                  <div class="no-data" v-else>
                    <el-empty :description="grabField.name + '暂无图片'" />
                  </div>
                </el-scrollbar>
              </div>
            </el-tab-pane>
            <el-tab-pane label="本地上传" name="2">
              <div class="inner-image-choose">
                <el-upload
                    v-model:file-list="imgUploadList"
                    class="uploader-content"
                    :action="actionUrl"
                    :before-upload="handleBeforeUpload"
                    :http-request="handleUpload"
                    :show-file-list="false"
                    accept="image/png, image/jpeg"
                    :limit="1"
                    :on-change="handleChangeFiles"
                    :on-exceed="handleExceed"
                >
                  <template #trigger>
                    <el-button type="primary" >上传图片</el-button>
                  </template>
                  <div class="upload-img-box">
                    <div v-for="(element,index) in imgUploadList" :key="index">
                      <li>
                        <div class="img-box">
                          <img :src="element.url" alt="">
                        </div>
                        <div class="progress-box" v-show="element.percentage !== 100">
                          <el-progress :percentage="element.percentage" :status="element.status === 'success' ? 'success' : ''" :stroke-width="20" :text-inside="true"/>
                        </div>
                        <div class="remove-upload" @click.stop="removeUpload(element.uid)">
                          <el-icon><Delete /></el-icon>
                        </div>
                      </li>
                    </div>
                  </div>
                </el-upload>
              </div>
            </el-tab-pane>
            <el-tab-pane label="素材库" name="3">
              <div class="inner-image-choose">
                <div class="material-choose-box">
                  <div class="btn" :class="{'is-active': thisLib === 1}" @click="changeLibrary(1)">个人资源库</div>
                  <div class="btn" :class="{'is-active': thisLib === 2}" @click="changeLibrary(2)">公共资源库</div>
                </div>
                <el-scrollbar height="432px">
                  <div class="thumb-list-box" v-if="materialImages.length > 0">
                    <div class="thumb-item" v-for="item in materialImages" :key="item.id" @click="chooseMaterial(item)">
                      <el-checkbox class="thumb-item-checkbox" :model-value="choseMaterialThumb[0].id === item.id"></el-checkbox>
                      <img :src="item.url" alt="">
                    </div>
                  </div>
                </el-scrollbar>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="image-choose-step2" v-if="thumbStep === 2">
          <div class="cropper-box">
            <div class="cropper">
              <vueCropper
                  ref="cropper"
                  :img="option.img"
                  :outputSize="option.size"
                  :outputType="option.outputType"
                  :autoCrop="true"
                  :fixed-number="imageScale"
                  :fixed="true"
                  mode="100%"
                  :centerBox="true"
                  @realTime="thumbPreview"
              ></vueCropper>
            </div>
            <div class="cropper-option">
              <el-icon @click="changeScale(1)"><ZoomIn /></el-icon>
              <el-icon @click="changeScale(-1)"><ZoomOut /></el-icon>
            </div>
          </div>
          <div class="thumb-preview" v-if="props.imageScale === 1">
            <p>封面裁剪</p>
            <div class="inner-thumb-preview">
              <div class="thumb-preview-item big-preview">
                <div class="img-box">
                  <div :style="previewStyle">
                    <div :style="previewImg.div">
                      <img :src="previewImg.url" :style="previewImg.img">
                    </div>
                  </div>
                </div>
                <div class="img-msg">
                  <p>新闻封面（16:9）</p>
                  <span>该内容在列表页中，将显示此类型封面缩略图</span>
                </div>
              </div>
              <div class="thumb-preview-item small-preview">
                <div class="img-box">
                  <div :style="previewStyle">
                    <div :style="previewImg.div">
                      <img :src="previewImg.url" :style="previewImg.img">
                    </div>
                  </div>
                </div>
                <div class="img-msg">
                  <p>新闻封面（4:3）</p>
                  <span>该内容在部分模板中，将显示此类型封面缩略图</span>
                </div>
              </div>
            </div>
          </div>
          <div class="thumb-preview" v-if="props.imageScale === 2">
            <p>图片裁剪</p>
            <div class="inner-thumb-preview">
              <div class="thumb-preview-item">
                <div class="img-box">
                  <div :style="previewStyle">
                    <div :style="previewImg.div">
                      <img :src="previewImg.url" :style="previewImg.img">
                    </div>
                  </div>
                </div>
              </div>
              <div class="img-msg">
                <p>图片比例（3:4）</p>
              </div>
            </div>
          </div>
        </div>
        <div class="footer-btn-box">
          <div class="inner-footer">
            <div class="left-btn-box">
              <el-button round v-if="thumbStep === 2" @click="prevStep">上一步</el-button>
            </div>
            <div class="right-btn-box">
              <el-button type="primary" round v-if="thumbStep === 1" :disabled="checkedThumb.length === 0" @click="nextStep">下一步</el-button>
              <el-button type="primary" round v-else @click="uploadThumb">确定</el-button>
              <el-button round @click="showThumbBox = false">取消</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </el-form-item>
</template>
<script setup>
import { reactive, ref, watch, computed, onMounted} from "vue";
import VueCropper from "vue-cropper/src/vue-cropper.vue";
import {getRandomString, transBase64FromImage} from "@/utils/tools";
import {fileMd5 ,splitUpload, singleUpload} from "@/utils/upload";

import { Plus,ZoomOut,ZoomIn,Delete } from '@element-plus/icons-vue';
import {ElMessage} from "element-plus";
import {getMaterial} from "@/api/content";
import { useStore } from "vuex"
const store = useStore()
const props = defineProps({
  content: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: ''
  },
  grabField: {
    type: Object,
    default: null
  },
  value: {
    type: String,
    default: ''
  },
  imageScale: {
    type: Number,
    default: 1
  },
  field: {
    type: String,
    default: ''
  },
  required: {
    type: Boolean,
    default: false
  },
})
// const actionUrl = ref('http://hms-localoss.foxtest.net/upload/d29eUgRWVgMBAAgBB1MEA1EHUgBUWlMCUAFSClYPVwoIBlVEUR4SDltAXxQAIg9GUVRABnRfXFMRUyFbWRMXU3ZFCwURUSVXXlMdBnQFClVMFlJyT1RGEAMnGlVHGxdTdkUVFhFRJUNBREAUACIVUlIWUnJDQEEQAycQWEZGBSdPXBVHAyUVRFcWTlBbCAFdUUpYUAJbUAEEXQMAB1UGAgEDVFoBBwUKAwBcBVFTVwRRCwcXQ1lXRgkRElVbAlZBAnYKDFgPCFYUB3tDUgwKQlEVElBDXUdYVRYJBAVFRQVBUBcPVRQNbFhdWVZSXA1CQENAAnYdB3MRViRRWRAfCFpWBA5bFRUdV19ARVISERhaVhEUBX4HBQZWUwgEWhdWcwRRUAdTXgoGBRZBWQZDQkZSC0JRXUdqRAoFBAVFUQtYRRcHRxU5QFhKXQwFUVUQV1wIQUVdRkZrFAdLVwZcEAgCVURHDxxWDAEIAwNR/')
const actionUrl = ref(store.state.content.uploadUrl)
store.dispatch('content/updateUploadUrl').then(res => {
  actionUrl.value = res.uploadUrl
})

const emit = defineEmits(['update:value'])
const content = ref(props.content)
const grabField = ref(props.grabField)
watch(props,(newVal) => {
  content.value = newVal.content
  grabField.value = newVal.grabField
},{deep: true})
// eslint-disable-next-line vue/return-in-computed-property
const imageScale = computed(() => {
  switch (props.imageScale){
    case 1:
      return [16,9]
    case 2:
      return [3,4]
  }
})
const handleShowThumbBox = () => {
  thumbList.value = []
  showThumbBox.value = true
  handleMaterial()
  let tinyCnt = content.value
  let imgList = []
  if(tinyCnt){
    imgList = tinyCnt.match(/<img[^>]+>/g)
  }
  if(imgList && imgList.length>0){
    imgList.forEach((item,index) => {
      item.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function(match, capture) {
        let imgObj = {
          id: index,
          url: capture
        }
        thumbList.value.push(imgObj)
      });
    })
    choseThumb.value = [thumbList.value[0]]
    checkedThumb.value = JSON.parse(JSON.stringify(choseThumb.value))
  }
}
const checkedThumb = ref([])
const showThumbBox = ref(false)
const thumbStep = ref(1)
const thumbSelectMenu = ref(grabField.value ? '1' : '2')
const setAvatarBase64 = (src) => {
  return new Promise((resolve) => {
    let image = new Image();
    // 处理缓存
    image.src = src + "?v=" + Math.random();
    // 支持跨域图片
    image.crossOrigin = "*";
    image.onload = () => {
      let base64 = transBase64FromImage(image);
      resolve(base64);
    };
  });
};
// 图片上传
const imgUploadList = ref([])
const uploadChose = ref([])

const handleBeforeUpload = async (file) => {
  let res = await fileMd5(file,actionUrl.value)
  if(res.data.length === 0){
    return true
  }else{
    imgUploadList.value.push({
      uid: file.uid,
      percentage: 100,
      url: res.data.url,
      name: file.name,
      status: 'success'
    })
    handleAvatarSuccess(res.data,file)
    return false
  }
};
const handleUpload = async (option) => {
  // 不切片
  if (option.file.size > 5 * 1024 * 1024) {
    let res = await splitUpload(option.file, actionUrl.value , option.onProgress, 5 * 1024 * 1024)
    handleAvatarSuccess(res,option.file)
  } else {
    let data = new FormData()
    data.append('file', option.file)
    data.append('name', option.file.name)
    data.append('size', option.file.size)
    data.append('lastModifiedDate', option.file.lastModifiedDate)
    let res = await singleUpload(data, actionUrl.value, option.onProgress)
    handleAvatarSuccess(res,option.file)
  }
}
const handleAvatarSuccess = (res,file) => {
  console.log(res,file)
  let _item = {
    id: file.uid,
    url: res.url
  }
  console.log(imgUploadList.value)
  uploadChose.value = [JSON.parse(JSON.stringify(_item))]
  checkedThumb.value = [JSON.parse(JSON.stringify(_item))]
}
const handleChangeFiles = (file) => {
  let URL = null;
  if (window.createObjectURL != undefined) {
    // basic
    URL = window.createObjectURL(file.raw);
  } else if (window.URL != undefined) {
    // mozilla(firefox)
    URL = window.URL.createObjectURL(file.raw);
  } else if (window.webkitURL != undefined) {
    // webkit or chrome
    URL = window.webkitURL.createObjectURL(file.raw);
  }
  file.url = URL
}
const removeUpload = (id) => {
  console.log(imgUploadList.value)
  imgUploadList.value = imgUploadList.value.filter(item => item.uid !== id)
}
const handleExceed = (files) => {
  if(process.env.NODE_ENV === 'development') console.log(files)
  ElMessage({
    showClose: true,
    message: '当前只允许上传1张图片',
    type: 'warning'
  })
}
// tab切换
const handleTabChange = (name) => {
  switch (name){
    case '1':
      checkedThumb.value = JSON.parse(JSON.stringify(choseThumb.value))
      break;
    case '3':
      checkedThumb.value = JSON.parse(JSON.stringify(choseMaterialThumb.value))
      break;
    case '2':
      checkedThumb.value = JSON.parse(JSON.stringify(uploadChose.value))
      break;
  }
}

// 资源切换
const thisLib = ref(1)
const materialImages = ref([])  //资源库图片列表

const getMeterialById = async (id) => {
  let res = await getMaterial({id})
  materialImages.value = res.data.map(item => {return {id: item.id,url:item.thumb}})
  choseMaterialThumb.value = [materialImages.value[0]]
}
const handleMaterial = () => {
  getMeterialById(1)
}
const choseMaterialThumb = ref([])

const changeLibrary = (id) => {
  thisLib.value = id
  getMeterialById(id)
}
const chooseMaterial = (item) => {
  choseMaterialThumb.value = [item]
  checkedThumb.value = [item]
}


// 正文图片选择
const thumbList = ref([]) //缩略图数组
const choseThumb = ref([])

const handleCloseThumbBox = () => {
  thumbStep.value = 1
}
const chooseThumb = (item) => {
  choseThumb.value = [item]
  checkedThumb.value = [item]
}
const nextStep = () => {
  thumbStep.value = 2
  setAvatarBase64(checkedThumb.value[0].url).then(base64 => {
    option.img = base64
  })
}
const prevStep = () => {
  thumbStep.value = 1
}

//缩略图裁剪
const cropper = ref()
const option = reactive({
  img: '',
  size: 1,
  outputType: 'jpg'
})
const previewImg = reactive({
  img: {},
  url: '',
  div: {},
})
const previewStyle = reactive({
  width: '',
  height: '',
  margin: 0,
  zoom: 1,
  overflow: "hidden"
})
const thumbPreview = (val) => {
  previewImg.img = val.img
  previewImg.url = val.url
  previewImg.div = val.div
  previewStyle.width = val.w + 'px'
  previewStyle.height = val.h + 'px'
  previewStyle.zoom = 90 / val.h
}
const changeScale = (val) => {
  cropper.value.changeScale(val)
}
const thumbImg = ref(props.value)
const uploadThumb = () => {
  cropper.value.getCropBlob(blob => {
    const xhr = new XMLHttpRequest()
    xhr.withCredentials = false
    xhr.open('POST', actionUrl.value ,true)
    xhr.onload = function() {
      if(xhr.status === 403){
        if(process.env.NODE_ENV === 'development') console.log('HTTP Error: ' + xhr.status);
        return
      }
      if(xhr.status < 200 || xhr.status >= 300){
        if(process.env.NODE_ENV === 'development') console.log('HTTP Error: ' + xhr.status);
        return
      }
      //注意json
      const json = JSON.parse(xhr.responseText);
      if(json.url && json.url != ''){
        thumbImg.value = json.url
        emit('update:value',thumbImg.value)
        showThumbBox.value = false
        handleCloseThumbBox()
      }
    }
    let formData = new FormData()
    let _fileName = '裁剪图片' + getRandomString(6) + '.jpg'
    formData.append('name',_fileName)
    formData.append('file', blob , _fileName)
    xhr.send(formData)
  })
}
const deleteThumb = () => {
  thumbImg.value = ''
  emit('update:value',thumbImg.value)
}
const textRule = ref([])
const validateThumb = (rule, value, callback) => {
  if (value === ''){
    callback(new Error(props.title+'不能为空'))
  } else {
    callback()
  }
}
onMounted(() => {
  if(props.required){
    textRule.value.push({validator: validateThumb,trigger: 'blur'})
  }
})
</script>
<style scoped lang="scss">
.thumb-img-box{
  border: 1px solid $borderColor;
  height: 120px;
  width: 176px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #F2F2F2;
  transition: all 0.3s;
  position: relative;
  img{
    width: 100%;
    height: 100%;
    max-height: 100%;
    max-width: 100%;
  }
  .delete-thumb{
    color: $white;
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    display: none;
    height: 24px;
    width: 24px;
    background-color: #FF5240;
    box-sizing: border-box;
    border: 1px solid rgba(255,255,255,0.5);
    align-items: center;
    justify-content: center;
    i{
      font-size: 16px;
    }
  }
  &:hover{
    box-shadow: 0 0 10px rgba(0,0,0,0.2);
    .delete-thumb{
      display: flex;
    }
  }
}
.thumb-img-box.thumb-img-box-2{
  height: 120px;
  width: 90px;
}
::v-deep(.thumb-tool-box .el-dialog__body){
  padding: 0;
}
.thumb-tool-box{
  .image-choose-content{
    .uploader-content{
      .upload-img-box{
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        &>div{
          height: 160px;
          width: 160px;
          margin-right: 20px;
          margin-top: 20px;
          background-color: #F8F8F8;
        }
        &>div:nth-child(5n+1){
          margin-left: 18px;
        }
        li{
          transition: all 0.3s;
          height: 160px;
          width: 160px;
          box-sizing: border-box;
          list-style: none;
          border: 1px solid #E4E4E4;
          display: flex;
          align-items: center;
          justify-content: center;
          position: relative;
          cursor: pointer;
          .img-box{
            height: 158px;
            width: 158px;
            display: flex;
            justify-content: center;
            align-items: center;
            img{
              max-width: 158px;
              max-height: 158px;
            }
          }
          .progress-box{
            width: 100%;
            position: absolute;
            bottom: 0;
            ::v-deep(.el-progress-bar__outer){
              border-radius: 0;
            }
            ::v-deep(.el-progress-bar__inner){
              border-radius: 0;
            }
          }
          .remove-upload{
            color: $white;
            position: absolute;
            right: 5px;
            top: 5px;
            cursor: pointer;
            display: none;
            height: 24px;
            width: 24px;
            background-color: #FF5240;
            box-sizing: border-box;
            border: 1px solid rgba(255,255,255,0.5);
            align-items: center;
            justify-content: center;
            i{
              font-size: 16px;
            }
          }
          &:hover{
            box-shadow: 0 0 10px rgba(0,0,0,0.2);
            border-color: $mainColor;
            background-color: $focusContent;
            .remove-upload{
              display: flex;
            }
          }
        }
      }
    }
    .inner-image-choose{
      padding: 0 20px;
      .material-choose-box{
        display: flex;
        margin-bottom: 10px;
        .btn{
          padding: 0 15px;
          line-height: 32px;
          height: 32px;
          border-radius: 100px;
          margin-right: 10px;
          cursor: pointer;
          border: 1px solid #C4C9D5;
        }
        .btn.is-active{
          background-color: $mainColor;
          border-color: $mainColor;
          color: $white;
        }
      }
    }
    h3{
      font-size: 14px;
      font-weight: normal;
      padding: 10px 0;
    }
    ::v-deep(.el-tabs__item.is-top:nth-child(2)){
      padding-left: 20px;
    }
    .image-choose-step1{
      .thumb-list-box{
        display: flex;
        flex-wrap: wrap;
        .thumb-item{
          position: relative;
          height: 160px;width: 160px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #F0F2F7;
          margin-right: 15px;
          margin-bottom: 15px;
          box-sizing: border-box;
          cursor: pointer;
          .thumb-item-checkbox{
            position: absolute;
            left: 5px;
            top: 0;

          }
          &.checked{
            border: 1px solid $mainColor;
          }
          &:nth-child(5n){
            margin-right: 0;
          }
          img{max-height: 100%;max-width: 100%;}
        }
      }
    }
    .image-choose-step2{
      display: flex;
      padding-top: 24px;
      justify-content: space-between;
      .cropper-box{
        width: 468px;
        .cropper{
          width: 100%;
          height: 430px;
        }
        .cropper-option{
          height: 40px;
          width: 100%;
          border-top: 1px solid #DCDFE6;
          background-color: $backBase;
          display: flex;
          justify-content: center;
          align-items: center;
          .el-icon{
            cursor: pointer;
            font-size: 24px;
          }
          .el-icon:nth-child(1){
            margin-right: 20px;
          }
        }
      }
      .thumb-preview{
        width: 374px;
        .inner-thumb-preview{
          .thumb-preview-item.big-preview{
            margin-top: 24px;
            .img-box{
              height: 90px;width: 160px;
              overflow: hidden;
            }
          }
          .thumb-preview-item.small-preview{
            margin-top: 30px;
            .img-box{
              height: 90px;width: 120px;
              overflow: hidden;
            }
          }
          .thumb-preview-item{
            display: flex;
            justify-content: space-between;
            .img-box img{max-width: none;}
            .img-msg{
              width: 210px;
              p{
                font-size: 14px;
                margin-bottom: 10px;
              }
              span{
                @include tipsText()
              }
            }
          }
        }
      }
    }
    .footer-btn-box{
      padding: 30px 20px;
      .inner-footer{
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
</style>
